import 'dart:convert';
import 'dart:core';

import 'package:decimal/decimal.dart';
import 'package:ecy_app_flutter/EcyRouter.dart';
import 'package:ecy_app_flutter/constant/EcyEventConsnt.dart';
import 'package:ecy_app_flutter/routes/goodscart/widgets/EcyGoodsCartItemWidget.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

import '../../constant/color_constant.dart';
import '../../ecycommon/EcyAPI.dart';
import '../../ecycommon/EcyCommonWidgets.dart';
import '../../ecycommon/EcyEventBus.dart';
import '../../ecycommon/EcyRequestBaseManager.dart';
import '../../model/EcyApiCommonResponse.dart';
import 'model/EcyGoodsCartListModel.dart';

class EcyGoodsCartHomePage extends EcyCommonBaseWidget {
  @override
  _EcyGoodsCartHomePageState createState() {
    return _EcyGoodsCartHomePageState(this);
  }
}

class _EcyGoodsCartHomePageState extends EcyCommonBaseWidgetState {
  EcyGoodsCartListModel cartgoods =
      EcyGoodsCartListModel(0, 0, false, [], false);
  late EcyCommonBaseWidget controller;
  _EcyGoodsCartHomePageState(EcyCommonBaseWidget vc) {
    controller = vc;
  }

  int _totalNumber = 0;
  Decimal _totalPrice = Decimal.zero;
  bool _selectAllFlag = false;

  @override
  void initState() {
    super.initState();
    requestData();
    _initNotis();
  }

  @override
  void requestData() async {
    super.requestData();
    var response = await EcyRequestbasemanager()
        .get("/app/api/app/cart", {"pageIndex": 1, "pageSize": 50});
    var _resp = EcyApiCommonResponse.fromJson(response, (response) => json);
    if (_resp.code == 200 || _resp.code == 0) {
      EcyGoodsCartListModel _cartgoods =
          EcyGoodsCartListModel.fromJson(response["data"]);
      setState(() {
        cartgoods = _cartgoods;
      });
    }
  }

  _initNotis() {
    EcyEventBus().on(EcyEventConst.kPaySuccess, (arg) {
      if (mounted) {
        requestData();
      }
    });
  }

  /// 商品数量加减 0:减 1:加
  Future<bool> operateCartQuantityRequest(String id, int operation) async {
    try {
      var response = await EcyRequestbasemanager().put("/app/api/app/cart",
          {"id": id, "operation": operation, "quantity": 1});
      var commonResponse = EcyApiCommonResponse.fromJson(response, (response) => json);
      if(commonResponse.code != 0 && commonResponse.code != 200) {
        EasyLoading.showToast(commonResponse.msg ?? "请稍后再试", duration: const Duration(seconds: 2));
        return false;
      }
      _selectCart();
      return true;
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
      return false;
    } finally {
      EcyEventBus().emit(EcyEventConst.kCartChanged);
    }
  }

  /// 删除购物车商品
  void _deleteCart(List<String> ids) async {
    if (ids.isEmpty) {
      EasyLoading.showToast("您还没有选择商品哦", duration: const Duration(seconds: 2));
      return;
    }
    setState(() {
      cartgoods.records?.removeWhere((item) => ids.contains(item.id));
      if ((cartgoods.records ?? []).isEmpty) {
        cartgoods.editing = false;
      }
    });
    _selectCart();
    try {
      var response =
          await EcyRequestbasemanager().delete(EcyAPI.deleteCart.url, ids);
      EcyApiCommonResponse.fromJson(response, (response) => json);
    } catch (e) {
      EasyLoading.showToast("请稍后再试", duration: const Duration(seconds: 2));
    } finally {
      EcyEventBus().emit(EcyEventConst.kCartChanged);
    }
  }

  /// 选中商品
  void _selectCart() {
    var cartList = cartgoods.records ?? [];
    if (cartList.isEmpty) {
      setState(() {
        _totalNumber = 0;
        _totalPrice = Decimal.zero;
        _selectAllFlag = false;
      });
    } else {
      var selectedCartList =
          cartList.where((n) => n.selected ?? false).toList();
      setState(() {
        _totalNumber = selectedCartList.length;
        _totalPrice = selectedCartList.isEmpty
            ? Decimal.zero
            : selectedCartList.map((n) {
                return (n.price??Decimal.zero) * Decimal.fromInt(n.quantity ?? 0);
              }).reduce((value1, value2) => value1 + value2);
        _selectAllFlag = selectedCartList.length == cartList.length;
      });
    }
  }

  void _selectAll() {
    var selectAllFlag = !_selectAllFlag;
    for (var n in (cartgoods.records ?? [])) {
      n.selected = selectAllFlag;
    }
    setState(() {
      _selectAllFlag = selectAllFlag;
      cartgoods = cartgoods;
    });
    _selectCart();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        backgroundColor: ColorConstant.White,
        appBar: AppBar(
            leading: IconButton(
              icon: const Icon(Icons.arrow_back_ios),
              onPressed: () {
                EcyRouter.pop(context, "");
              },
              tooltip: MaterialLocalizations.of(context).openAppDrawerTooltip,
            ),
            backgroundColor: const Color(0xFFFFF0F8),
            centerTitle: true,
            title: Text(
              "购物车",
              style: TextStyle(
                  fontFamily: "PingFang SC",
                  color: const Color(0xD9000000),
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w700),
            ),
            actions: [
              GestureDetector(
                  onTap: () {
                    if (cartgoods.editing == null) {
                      cartgoods.editing = true;
                    } else {
                      cartgoods.editing = !cartgoods.editing!;
                    }
                    setState(() {
                      cartgoods = cartgoods;
                    });
                  },
                  child: Container(
                    margin: EdgeInsets.only(
                        left: 8.w, right: 16.w, top: 8.h, bottom: 8.h),
                    child: Text(
                      (cartgoods.editing ?? false) ? "完成" : "管理",
                      style: TextStyle(
                          fontFamily: "PingFang SC",
                          color: cartgoods.editing ?? false
                              ? const Color(0xFFEA4B9B)
                              : const Color(0xFF262626),
                          fontSize: 16.sp,
                          fontWeight: FontWeight.w700),
                    ),
                  ))
            ]),
        body: Container(
            width: EcyPageUtil.screenWidth(context),
            height: EcyPageUtil.screenHeight(context),
            decoration: const BoxDecoration(
              gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment(
                      0.5, 0.3), // 10% of the width, so there are ten blinds.
                  colors: [
                    Color(0xFFFFEEF7),
                    Color(0x00F5F5F5)
                  ] // repeats the gradient over the canvas
                  ),
            ),
            child: Column(
              children: [
                Expanded(
                    child: Container(
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8.r),
                    color: ColorConstant.White,
                  ),
                  margin: EdgeInsets.only(
                      left: 8.w, right: 8.w, top: 8.h, bottom: 8.h),
                  width: MediaQuery.of(context).size.width - 16.w,
                  padding: EdgeInsets.only(
                      left: 8.w, right: 8.w, top: 8.w, bottom: 8.w),
                  child: ListView.builder(
                      shrinkWrap: true,
                      physics: const AlwaysScrollableScrollPhysics(),
                      scrollDirection: Axis.vertical,
                      itemCount: cartgoods.records?.length,
                      itemBuilder: (context, index) {
                        var item = cartgoods.records?[index];
                        item?.editing = cartgoods.editing;
                        return EcyGoodsCartItemWidget(
                          item!,
                          (onCheckValue) {},
                          (onOpeNumlValue) {
                            return operateCartQuantityRequest(
                                onOpeNumlValue.id!, onOpeNumlValue.operation!);
                          },
                          (onSelectValue) {
                            _selectCart();
                          },
                          (onDelOneValue) {
                            if (item.id != null) {
                              _deleteCart([item.id!]);
                            }
                          },
                          cartgoods.editing ?? false,
                          key: Key(item.id ?? ""),
                        );
                      }),
                )),
                Container(
                    margin: EdgeInsets.only(
                        left: 16.w,
                        right: 16.w,
                        top: 16.w,
                        bottom:
                            EcyPageUtil.getBottomSafeHeight(context).h + 20),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceAround,
                      children: [
                        Expanded(
                            child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          crossAxisAlignment: CrossAxisAlignment.center,
                          children: [
                            GestureDetector(
                                onTap: () {
                                  _selectAll();
                                },
                                child: Image(
                                    image: AssetImage(_selectAllFlag ?? false
                                        ? 'assets/images/login_checked.png'
                                        : 'assets/images/login_unchecked.png'),
                                    width: 20.w,
                                    height: 20.w)),
                            GestureDetector(
                                onTap: () {
                                  _selectAll();
                                },
                                child: Text('全选',
                                    textAlign: TextAlign.center,
                                    style: TextStyle(
                                        fontFamily: "PingFang SC",
                                        fontWeight: FontWeight.w500,
                                        fontSize: 14.sp,
                                        color: const Color(0xFF8C8C8C))),),
                            SizedBox(width: 15.w),
                            if (!(cartgoods.editing ?? false))
                              Align(
                                alignment: Alignment.bottomCenter,
                                child: Row(
                                  children: [
                                    Text('已选$_totalNumber件,',
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 14.sp,
                                            color: const Color(0xFF8C8C8C))),
                                    Text("合计:",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w500,
                                            fontSize: 14.sp,
                                            color: const Color(0xFF8C8C8C))),
                                    Text(" ¥ ",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w700,
                                            fontSize: 14.sp,
                                            color: const Color(0xFFF55F4E))),
                                    Text("$_totalPrice",
                                        textAlign: TextAlign.center,
                                        style: TextStyle(
                                            fontFamily: "PingFang SC",
                                            fontWeight: FontWeight.w700,
                                            fontSize: 18.sp,
                                            color: const Color(0xFFF55F4E))),
                                  ],
                                ),
                              ),
                          ],
                        )),
                        GestureDetector(
                            onTap: () {
                              // 删除
                              if (cartgoods.editing ?? false) {
                                var selectedCartIdList = (cartgoods.records ??
                                        [])
                                    .where((n) =>
                                        n.id != null && (n.selected ?? false))
                                    .map((e) => e.id!)
                                    .toList();
                                _deleteCart(selectedCartIdList);
                                return;
                              }
                              // 去结算
                              var selectedGoods = (cartgoods.records??[]).where((e) => e.selected??false);
                              if(selectedGoods.isEmpty) {
                                EasyLoading.showToast("请选择商品哦", duration: const Duration(seconds: 2));
                                return;
                              }
                              var goods = [];
                              for (var item in selectedGoods) {
                                var cartNum = item.quantity ?? 1;
                                var price = item.price;
                                var totalPrice =
                                    Decimal.parse(cartNum.toString()) *
                                        (price ?? Decimal.zero);
                                goods.add({
                                  "id": item.id,
                                  "skuId": item.skuId,
                                  "price": double.parse(price.toString()),
                                  "salePrice": double.parse(price.toString()),
                                  "num": cartNum,
                                  "totalPrice": double.parse(totalPrice.toString()),
                                  "imageUrl": item.image,
                                  "skuName": item.productName,
                                  "selectNum": cartNum,
                                });
                              }
                              var msg = {"shopId": "5", "cartFlag": true, "skuList": goods};
                              EcyRouter.push(context, EcyRouter.orderConfirm,
                                  json.encode(msg));
                            },
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(26.r),
                                color: ColorConstant.CommonColor,
                              ),
                              width: 80.w,
                              height: 40.h,
                              alignment: Alignment.center,
                              child: Text(
                                  (cartgoods.editing ?? false) ? '删除' : '去结算',
                                  textAlign: TextAlign.center,
                                  style: TextStyle(
                                      fontFamily: "PingFang SC",
                                      fontWeight: FontWeight.w700,
                                      fontSize: 16.sp,
                                      color: ColorConstant.White)),
                            ))
                      ],
                    )),
              ],
            )));
  }
}
